<?php

/**
  +------------------------------------------------------------------------------
 * 后台信息管理
  +------------------------------------------------------------------------------
 * @copyright   2012 友拓软件友拓通
 * @category  	 基本信息
 * @package  	Model
 * @author    	黄明兴
 * @version 	2012-07-10
  +------------------------------------------------------------------------------
 */
class AdminModel extends Model {

    // 指定表名
    protected $tableName = 'config';
    public $lang = array();

    /**
     * 获取所有节点信息，用于模块开启，关闭
     *
     * @return uarray
     */
    public function getNode() {
        $list = M(C('RBAC_NODE_TABLE'))->where('level=1 and is_user=1 and group_id=0')->select();
        $menu = array();
        foreach ($list as $key => $value) {
            if ($value['id'] == 7) {
                $list2 = M(C('RBAC_NODE_TABLE'))->where('is_user=1 and group_id>0 and parent_id=7')->select();
                foreach ($list2 as $value2) {
                    $menu[$value2['id']] = $value2;
                    $sql = 'select * from node where is_user=1 and level=2 and group_id>0 and parent_id =\'' . $value2['id'] . '\' order by sort asc';
                    $list3 = $this->query($sql);
                    $menu[$value2['id']]['sub'] = $list3;
                }
            } else {
                $menu[$value['id']] = $value;
                $sql = 'select * from node where is_user=1 and level=2 and group_id>0 and (parent_id in (select id from node where parent_id=\'' . $value['id'] . '\') or parent_id=\'' . $value['id'] . '\') order by sort asc';
                $list2 = $this->query($sql);
                $menu[$value['id']]['sub'] = $list2;
            }
        }
        return $menu;
    }

    /**
     * 保存模块信息信息
     *
     * @return  bool
     */
    public function saveNode() {
        // 设置所有菜单为不可用
        $this->query('update ' . C('RBAC_NODE_TABLE') . ' set status=0');
        // 设置已选菜单可用
        foreach ($_POST['flow'] as $id => $value) {
            $this->query('update ' . C('RBAC_NODE_TABLE') . ' set status=1 where id=' . $id);
        }
        // 设置可用菜单的关联菜单可用(上级和下级)
        $list = $this->query('select * from ' . C('RBAC_NODE_TABLE') . ' where status=1');
        foreach ((array) $list as $value) {
            $this->query('update ' . C('RBAC_NODE_TABLE') . ' set status=1 where parent_id=' . $value['id'] . ' or id=' . $value['parent_id']);
        }
        // 重复执行一次确保一级菜单勾选（只更新上级）
        $list = $this->query('select * from ' . C('RBAC_NODE_TABLE') . ' where status=1');
        foreach ((array) $list as $value) {
            $this->query('update ' . C('RBAC_NODE_TABLE') . ' set status=1 where id=' . $value['parent_id']);
        }
        // 设置公共菜单可用
        $this->query('update ' . C('RBAC_NODE_TABLE') . ' set status=1 where module=\'Public\'');
        $list = $this->query('select id from ' . C('RBAC_NODE_TABLE') . ' where module=\'Public\'');
        $this->query('update ' . C('RBAC_NODE_TABLE') . ' set status=1 where parent_id=' . $list[0]['id']);
        return true;
    }

    /**
     * 保存配置信息
     *
     * @return bool
     */
    public function saveConfig() {
        $type = $_POST['type'];
        $type_key = intval($_POST['type_key']);
        if (empty($type))
            halt('无法获取配置类型，请检查type值是否正确。');
        unset($_POST['type'], $_POST['type_key'], $_POST['__hash__']);
        $this->where('type=\'' . $type . '\'')->delete();
        foreach ($_POST as $key => $value) {
            if (is_array($value) && !empty($value)) {
                $value = implode(',', $value);
            }
            $this->add(array('key' => $key, 'value' => $value, 'type' => $type, 'type_key' => $type_key));
        }
        $this->updateInvoiceNode();
        $this->updateCofig();
        return true;
    }

    public function updateCofig() {
        $list = $this->select();
        $config = array();
        foreach ($list as $key => $value) {
            if ($value['type_key'] == 1) {
                $config[$value['type']][$value['key']] = $value['value'];
            } else {
                $config[$value['key']] = $value['value'];
            }
        }
        /// 删除缓存的runtime文件
        @unlink(RUNTIME_FILE);
        $barcode_list = $this->getBarcodeList();
        $config = @array_merge((array) $barcode_list, (array) $config);
        file_put_contents(CONFIG_FILE, '<?php return ' . var_export($config, true) . ';?>');
    }

    public function getBarcodeList() {
        $info = M('barcodeRules')->select();
        foreach ((array) $info as $k => $value) {
            if ($value['key'] == 'barcode_length') {
                $list[$value['type']]['barcode_length'] = $value['value'];
                unset($info[$k]);
            } elseif ($value['key'] == 'is_comma') {
                $list[$value['type']]['is_comma'] = $value['value'];
                unset($info[$k]);
            } elseif ($value['key'] == 'country_no') {
                $list[$value['type']]['country_no'] = $value['value'];
                unset($info[$k]);
            } else {
                $list[$value['type']]['barcode'][$value['key']] = $value['value'];
                $list[$value['type']]['barcode_exchange'][$value['key']] = $value['is_exchange'];
                unset($info[$k]);
            }
        }
        return $list;
    }

    public function updateCurrency($data) {
        $temp_currendy = array();
        $data['client_currency'] && $temp_currendy = array_merge($temp_currendy, $data['client_currency']);
        $data['factory_currency'] && $temp_currendy = array_merge($temp_currendy, $data['factory_currency']);
        $data['logistics_currency'] && $temp_currendy = array_merge($temp_currendy, $data['logistics_currency']);
        $data['company_currency'] && $temp_currendy = array_merge($temp_currendy, $data['company_currency']);
        $temp_currendy = array_unique($temp_currendy);
        $_POST['client_currency_count'] = count($_POST['client_currency']);
        $_POST['factory_currency_count'] = count($_POST['factory_currency']);
        $_POST['logistics_currency_count'] = count($_POST['logistics_currency']);
        $_POST['company_currency_count'] = count($_POST['company_currency']);

        if (!empty($temp_currendy)) {
            M('Currency')->execute('update __TABLE__ set is_delete = 2');
            M('Currency')->execute('update __TABLE__ set is_delete = 1 where id in(' . implode(',', $temp_currendy) . ')');
        }
        return true;
    }

    /**
     * 增加条形码业务规则
     *
     * @param unknown_type $info
     */
    public function addConfigBarcode($info) {
        $db = Db::getInstance(C('RBAC_DB_DSN'));
        $type_key = intval($info['type_key']);
        $type = $info['type'];
        unset($info['type'], $info['type_key'], $info['__hash__']);
        M('barcode_rules')->where('type_key=' . $type_key)->delete();
        $info['barcode_length'] && $db->insert(array('key' => 'barcode_length', 'value' => intval($info['barcode_length']), 'is_exchange' => 0, 'type' => $type, 'type_key' => $type_key), array('table' => 'barcode_rules'));
        $info['is_comma'] && $db->insert(array('key' => 'is_comma', 'value' => $info['is_comma'], 'is_exchange' => 0, 'type' => $type, 'type_key' => $type_key), array('table' => 'barcode_rules'));
        $info['country_no'] && $db->insert(array('key' => 'country_no', 'value' => $info['country_no'], 'is_exchange' => 0, 'type' => $type, 'type_key' => $type_key), array('table' => 'barcode_rules'));
        $total_length = 0;
        foreach ((array) $_POST['detail'] as $key => $value) {
            if (empty($value['right_id']))
                continue;
            $total_length += intval($value['len']);
            $db->insert(array('key' => $value['right_id'], 'value' => $value['len'], 'is_exchange' => intval($value['is_exchange']), 'type' => $type, 'type_key' => $type_key), array('table' => 'barcode_rules'));
        }
        if (intval($info['barcode_length']) < $total_length) {
            redirect('barcode', 2, '条形码总长度大于输入的最大值!');
        }
        $this->updateCofig();
    }

    public function getBarcode() {
        $info = M('barcodeRules')->select();
        foreach ((array) $info as $key => $value) {
            if ($value['key'] == 'barcode_length')
                $list['barcode_length'] = $value['value'];
            elseif ($value['key'] == 'is_comma')
                $list['is_comma'] = $value['value'];
            elseif ($value['key'] == 'country_no')
                $list['country_no'] = $value['value'];
            else
                $list['detail'][] = $value;
        }
        return $list;
    }

    public function saveTemplete($info, $filename) {
        ini_set('memory_limit', '64M');
        @unlink(ADMIN_RUNTIME_PATH . 'Data/Excel/' . $filename . '.xls');
        addLang('product,common');
//		if (STORAGE_FORMAT==2) {
//			L('capability',L('storage_1'));
//		}else{
//			L('capability',L('storage_2'));
//			L('dozen',L('storage_3'));
//		}
        vendor('PhpExcel.PHPExcel', '', '.php');
        $objPHPExcel = new PHPExcel();
        // 设置excel文件信息
        $objPHPExcel->getProperties()->setCreator("dzh")->setTitle("Excel模板");
        $objPHPExcel->createSheet(0);
        $qt = 'A';
        $objActSheet = $objPHPExcel->setActiveSheetIndex(0);
        foreach ($info as $key => $value) {
            if ($filename == 'InitStorage' || $filename == 'Stocktake' || $filename == 'Product') {
                switch ($value[0]) {
                    case 'color_name':
                        if ($filename == 'Product') {
                            $title = '颜色';
                        } else {
                            if (C($filename . '.color') == 1) {
                                $title = L('color_name');
                            } else {
                                $title = '1';
                            }
                        }
                        break;
                    case 'size_name':
                        if ($filename == 'Product') {
                            $title = '尺码';
                        } else {
                            if (C($filename . '.size') == 1) {
                                $title = L('size_name');
                            } else {
                                $title = '1';
                            }
                        }
                        break;
                    case 'quantity':
                        if (C($filename . '.storage_format') == 1) {
                            $title = '数量';
                        } else {
                            $title = '箱数';
                        }
                        break;
                    case 'capability':
                        if ($filename == 'Product') {
                            $title = '每箱数量';
                        } else {
                            if (C($filename . '.storage_format') == 2)
                                $title = '每箱数量';
                            else
                                $title = '1';
                        }
                        break;
                    case 'dozen':
                        if ($filename == 'Product') {
                            $title = '每包数量';
                        } else {
                            if (C($filename . '.storage_format') == 3)
                                $title = '每包数量';
                            else
                                $title = '1';
                        }
                        break;
                    case 'quantity_state':
                        if (C($filename . '.mantissa') == 1)
                            $title = '尾箱';
                        else
                            $title = '1';
                        break;
                    default:
                        $title = L($value[0]);
                        break;
                }
            }else {
                $title = L($value[0]);
            }
            if ($title != 1) {
                $objActSheet->setCellValue($qt . '1', $title);
                $objActSheet->getColumnDimension($qt)->setWidth(strlen($title) + 2);
                $objStyle = $objActSheet->getStyle($qt . '1');


                $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $objStyle->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
                if ($value[1] == 1) {
                    $objStyle->getFont()->getColor()->setARGB('FFff0000');
                }
                $objPHPExcel->getActiveSheet()->getStyle($qt)->getNumberFormat()->setFormatCode("@");
                $qt++;
            }
            $title = '';
        }
        // 设置文件格式为Excel5
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save(ADMIN_RUNTIME_PATH . 'Data/Excel/' . $filename . '.xls');
    }

    public function saveExcelAry($data) {
        $ary = array();
        // 国家、城市
        $ary['District'][1] = array('country_name', 1, 'district_name');
        $ary['District'][2] = array('city_name', 0);
        // 员工
        $ary['Employee'][1] = C('SETAUTO_EMPLOYEE_NO') ? array('employee_no', 0) : array('employee_no', 1);
        $ary['Employee'][2] = array('employee_name', 1);
        $ary['Employee'][3] = array('sex', 0);
        $ary['Employee'][4] = array('department_name', 0);
        $ary['Employee'][5] = array('position_name', 0);
        $ary['Employee'][6] = array('phone', 0);
        $ary['Employee'][7] = array('email', 0);
        $ary['Employee'][8] = array('entry_date', 1);
        $ary['Employee'][9] = array('leave_date', 0);
        $ary['Employee'][10] = array('comments', 0);
        // 颜色
        $ary['Color'][1] = C('SETAUTO_COLOR_NO') ? array('color_no', 0) : array('color_no', 1);
        $ary['Color'][2] = array('color_name', 1);
        // 尺码
        $ary['Size'][1] = C('SETAUTO_SIZE_NO') ? array('size_no', 0) : array('size_no', 1);
        $ary['Size'][2] = array('size_name', 1);
        // 产品
        $ary['Product'][1] = C('SETAUTO_PROPERTIES_NO') ? array('product_no', 0) : array('product_no', 1);
        $ary['Product'][2] = array('product_name', 1);
        $ary['Product'][3] = array('class_name', 1);
        if (C('PRODUCT_FACTORY') == 1) {
            $ary['Product'][4] = array('factory_name', 1);
        }
        $ary['Product'][5] = array('instock_price', 0);
        $ary['Product'][6] = array('wholesale_price', 0);
        $ary['Product'][7] = array('retail_price', 0);
        $ary['Product'][8] = array('sale_price', 0);
        if (C('product_color') == 1) {
            $ary['Product'][9] = C('PRODUCT_COLOR') ? array('color_name', 1) : array('color_name');
        }
        if (C('product_size') == 1) {
            $ary['Product'][10] = C('PRODUCT_SIZE') ? array('size_name', 1) : array('size_name');
        }
        if (C('storage_format') == 2) {
            $ary['Product'][11] = array('capability', 1);
        }

        if (C('storage_format') == 3) {
            $ary['product'][12] = array('dozen', 1);
        }
        // 客户
        $ary['Client'][1] = C('SETAUTO_CLIENT_NO') ? array('comp_no', 0) : array('comp_no', 1, 'comp_no');
        $ary['Client'][2] = array('client_name', 1, 'comp_name');
        $ary['Client'][3] = array('tax_no', 0);
        $ary['Client'][4] = array('country_name', 0);
        $ary['Client'][5] = array('city_name', 0);
        $ary['Client'][6] = array('remind_day', 0);
        $ary['Client'][7] = array('credit', 0);
        $ary['Client'][8] = array('contact', 0);
        $ary['Client'][9] = array('mobile', 0);
        $ary['Client'][10] = array('phone', 0);
        $ary['Client'][11] = array('address', 0);
        $ary['Client'][12] = array('post_code', 0);
        $ary['Client'][13] = array('fax', 0);
        $ary['Client'][14] = array('email', 0);
        $ary['Client'][15] = array('comments', 0);
        // 厂家
        $ary['Factory'][1] = C('SETAUTO_FACTORY_NO') ? array('comp_no', 0) : array('comp_no', 1, 'comp_no');
        $ary['Factory'][2] = array('factory_name', 1, 'comp_name');
        $ary['Factory'][3] = array('currency_name', 1);
        $ary['Factory'][4] = array('country_name', 0);
        $ary['Factory'][5] = array('city_name', 0);
        $ary['Factory'][6] = array('remind_day', 0);
        $ary['Factory'][7] = array('contact', 0);
        $ary['Factory'][8] = array('mobile', 0);
        $ary['Factory'][9] = array('phone', 0);
        $ary['Factory'][10] = array('address', 0);
        $ary['Factory'][11] = array('post_code', 0);
        $ary['Factory'][12] = array('fax', 0);
        $ary['Factory'][13] = array('email', 0);
        $ary['Factory'][14] = array('comments', 0);
        // 其它往来单位
        $ary['OtherCompany'][1] = C('SETAUTO_OTHERCOMPANY_NO') ? array('comp_no', 0) : array('comp_no', 1, 'comp_no');
        $ary['OtherCompany'][2] = array('other_company_name', 1, 'comp_name');
        $ary['OtherCompany'][3] = array('country_name', 0);
        $ary['OtherCompany'][4] = array('city_name', 0);
        $ary['OtherCompany'][5] = array('remind_day', 0);
        $ary['OtherCompany'][6] = array('contact', 0);
        $ary['OtherCompany'][7] = array('mobile', 0);
        $ary['OtherCompany'][8] = array('phone', 0);
        $ary['OtherCompany'][9] = array('address', 0);
        $ary['OtherCompany'][10] = array('post_code', 0);
        $ary['OtherCompany'][11] = array('fax', 0);
        $ary['OtherCompany'][12] = array('email', 0);
        $ary['OtherCompany'][13] = array('comments', 0);
        // 期初库存
        $ary['InitStorage'][1] = array('product_name', 1, 'product_no');
        if (C('initStorage.color') == 1) {
            $ary['InitStorage'][2] = array('color_name', 1);
        }
        if (C('initStorage.size') == 1) {
            $ary['InitStorage'][3] = array('size_name', 1);
        }
        $ary['InitStorage'][4] = array('quantity', 1);
        $ary['InitStorage'][5] = array('capability', 1);
        if (C('initStorage.storage_format') == 3) {
            $ary['InitStorage'][6] = array('dozen', 1);
        }
        $ary['InitStorage'][7] = array('price', 1);
        if (C('initStorage.mantissa') == 1) {
            $ary['InitStorage'][8] = array('quantity_state', 1);
        }
        // 库存盘点
        $ary['Stocktake'][1] = array('product_name', 1, 'product_no');
        if (C('stocktake.color') == 1) {
            $ary['Stocktake'][2] = array('color_name', 1);
        }
        if (C('stocktake.size') == 1) {
            $ary['Stocktake'][3] = array('size_name', 1);
        }
        $ary['Stocktake'][4] = array('quantity', 1);
        $ary['Stocktake'][5] = array('capability', 1);
        if (C('stocktake.storage_format') == 3) {
            $ary['Stocktake'][6] = array('dozen', 1);
        }
        $ary['Stocktake'][7] = array('price', 1);
        if (C('Stocktake.mantissa') == 1) {
            $ary['Stocktake'][8] = array('quantity_state', 1);
        }
        // 厂家期初欠款
        $ary['FactoryIni'][1] = array('factory_name', 1, 'comp_name');
        $ary['FactoryIni'][3] = array('paid_date', 1);
        $ary['FactoryIni'][4] = array('currency_name', 1);
        $ary['FactoryIni'][5] = array('money', 1,);
        $ary['FactoryIni'][6] = array('comments', 0);
        // 客户期初欠款
        $ary['ClientIni'][1] = array('client_name', 1);
        $ary['ClientIni'][2] = array('company_name', 1);
        $ary['ClientIni'][3] = array('paid_date', 1);
        $ary['ClientIni'][4] = array('currency_name', 1);
        $ary['ClientIni'][5] = array('money', 1);
        $ary['ClientIni'][6] = array('comments', 0);
        //配镜档案
//        echo '<pre>';print_r($ary);exit;
        $ary    = array_merge($ary,$this->getGlassData());
        file_put_contents(ADMIN_RUNTIME_PATH . '~ExcelTemplete.php', "<?php\nreturn " . var_export($ary, true) . "\n?>");
    }

    public function importLang($path) {
        if (empty($path)) {
            return;
        }
        $lang = getAllFile($path, true);

        foreach ($lang as $key => $val) {
            if (strpos($val, '.php')) {
                $temp = include($path . $val);
                $arr = array_filter(explode('/', $path));
                if (count($arr) > 6) {
                    $type = end($arr);
                } else {
                    $type = str_replace('.php', '', $val);
                }
                $this->addLangToDb($temp, str_replace('.php', '', $val), $type);
            } else {
                $this->importLang($path . $val . '/');
            }
        }
    }

    /**
     * 语言包加入DB
     *
     * @param unknown_type $lang
     */
    public function addLangToDb($lang, $module, $type) {
        foreach ($lang as $k => $v) {
            $data['module'] = $module;
            $data['lang_key'] = $k;
            $data['lang_value_' . $type] = $v;
            $data['is_public'] = 1;
            M('lang')->data($data)->add();
            unset($data);
        }
    }

    public function updateInvoiceNode() {
        foreach ($_POST as $key => $val) {
            switch ($key) {
                case 'product_from':
                    if ($val == 1)
                        $id_0 [] = 196;
                    else
                        $id_1 [] = 196;
                    break;
                case 'client_from':
                    if ($val == 1)
                        $id_0 [] = 202;
                    else
                        $id_1 [] = 202;
                    break;
                case 'factory_from':
                    if ($val == 1)
                        $id_0 [] = 201;
                    else
                        $id_1 [] = 201;
                    break;
                case 'company_from':
                    if ($val == 1)
                        $id_0 [] = 198;
                    else
                        $id_1[] = 198;
                    break;
                default:
                    break;
            }
        }
        if (!empty($id_0)) {
            $ids = implode(',', $id_0);
            $where = 'id in (' . $ids . ') or parent_id in (' . $ids . ')';
            M('node')->where($where)->setField('status', 0);
        }
        if (!empty($id_1)) {
            $ids = implode(',', $id_1);
            $where = 'id in (' . $ids . ') or parent_id in (' . $ids . ')';
            M('node')->where($where)->setField('status', 1);
        }
    }

    /**
     * 根据配置模块获取相应配置值  一维数据
     * @param  string  $module
     * @return  array 
     */
    public function getModuleConf($module) {
        $temp = $this->where('type=\'' . $module . '\'')->select();
        $list = array();
        foreach ($temp as $value) {
            $list[$value['key']] = $value['value'];
        }
        return $list;
    }
    
    public function getGlassData(){
        return D('Glass')->getGlassData();
    }

}